package com.deyou.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deyou.Constants;
import com.deyou.R;
import com.deyou.activity.PayOrderActivity;
import com.deyou.base.BaseFragment;
import com.deyou.callback.ServerApi;
import com.deyou.model.HouseResourceDetailBean;
import com.deyou.model.LzyResponse;
import com.deyou.model.PayInfoBean;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.DateUtil;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.deyou.widget.CircleImageView;
import com.google.gson.jpush.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class OrderFragment extends BaseFragment {

    @BindView(R.id.iv_house)
    ImageView ivHouse;
    @BindView(R.id.tv_house_intro)
    TextView tvHouseIntro;
    @BindView(R.id.tv_house_rental_mode)
    TextView tvHouseRentalMode;
    @BindView(R.id.tv_rent_price)
    TextView tvRentPrice;
    @BindView(R.id.house_detail_item)
    LinearLayout houseDetailItem;
    @BindView(R.id.iv_house_owner)
    CircleImageView ivHouseOwner;
    @BindView(R.id.tv_owner_name)
    TextView tvOwnerName;
    @BindView(R.id.iv_chat_with_landload)
    ImageView ivChatWithLandload;
    @BindView(R.id.iv_callto_landload)
    ImageView ivCalltoLandload;
    @BindView(R.id.tv_house_addr)
    TextView tvHouseAddr;
    @BindView(R.id.tv_checkin_date)
    TextView tvCheckinDate;
    @BindView(R.id.tv_total_staydays)
    TextView tvTotalStaydays;
    @BindView(R.id.tv_checkout_date)
    TextView tvCheckoutDate;
    @BindView(R.id.tv_people_count)
    TextView tvPeopleCount;
    @BindView(R.id.tv_total_money_title)
    TextView tvTotalMoneyTitle;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_house_fee_titel)
    TextView tvHouseFeeTitel;
    @BindView(R.id.tv_total_house_fee)
    TextView tvTotalHouseFee;
    @BindView(R.id.tv_clean_fee_titel)
    TextView tvCleanFeeTitel;
    @BindView(R.id.tv_clean_fee)
    TextView tvCleanFee;
    @BindView(R.id.btn_apply_house)
    TextView btnApplyHouse;
    @BindView(R.id.contact_server_layout)
    RelativeLayout contactServerLayout;
    Unbinder unbinder;
    private Context mContext;

    private int checkinPeoPles;
    private String checkInDate, checkOutDate;
    private HouseResourceDetailBean detailBean;
    private long days;

    public static OrderFragment newInstance(String checkInDate, String checkOutDate, HouseResourceDetailBean detail, int stayPeople) {
        Bundle args = new Bundle();
        args.putString("in_date", checkInDate);
        args.putString("out_date", checkOutDate);
        args.putInt("stay_people", stayPeople);
        args.putSerializable("house_detail", detail);
        OrderFragment fragment = new OrderFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        this.mContext = context;
        super.onAttach(context);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        checkinPeoPles = getArguments().getInt("stay_people");
        checkInDate = getArguments().getString("in_date");
        checkOutDate = getArguments().getString("out_date");
        detailBean = (HouseResourceDetailBean) getArguments().getSerializable("house_detail");

        if (null != detailBean) {
            if (null != detailBean.picList && null != detailBean.picList.get(0) && !TextUtils.isEmpty(detailBean.picList.get(0).resourcePic)) {
                new GlideImageLoader().displayImage(mContext, Urls.HouseResourceImageBaseUrl + detailBean.picList.get(0).resourcePic, ivHouse);
            } else {
                new GlideImageLoader().displayImage(mContext, R.drawable.img_default, ivHouse);
            }
            tvHouseIntro.setText(detailBean.resourceName);
            tvHouseRentalMode.setText(detailBean.resourceTypeName + "-" + detailBean.resourceRentaltypeName);
            tvRentPrice.setText(Constants.RMB_UNIT + detailBean.resourcePrice);

            tvOwnerName.setText("房东：" + detailBean.resourceUserName);
            if (!TextUtils.isEmpty(detailBean.userPic))
                new GlideImageLoader().displayImage(mContext, Urls.UserImageBaseUrl + detailBean.userPic, ivHouseOwner);
            else
                new GlideImageLoader().displayImage(mContext, R.drawable.ic_default_avatar2, ivHouseOwner);
            tvHouseAddr.setText("地址：" + detailBean.resourceCityName + " " + detailBean.resourceRegionName + " " + detailBean.resourceAddress);

            tvCheckinDate.setText("入住时间：" + checkInDate);
            tvCheckoutDate.setText("退房时间：" + checkOutDate);
            tvPeopleCount.setText("入住人数：" + checkinPeoPles);

            days = (DateUtil.string2Date10(checkOutDate).getTime() - DateUtil.string2Date10(checkInDate).getTime()) / (1000 * 60 * 60 * 24);
            tvTotalStaydays.setText("共：" + days + "晚");

            tvHouseFeeTitel.setText(Constants.RMB_UNIT + detailBean.resourcePrice + "*" + days + "晚");
            tvTotalHouseFee.setText(Constants.RMB_UNIT + " " + (detailBean.resourcePrice * days));
            tvCleanFee.setText(Constants.RMB_UNIT + " 0");
            tvTotalMoney.setText(Constants.RMB_UNIT + " " + detailBean.resourcePrice * days);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_chat_with_landload, R.id.iv_callto_landload, R.id.contact_server_layout, R.id.btn_apply_house})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_chat_with_landload:
                break;
            case R.id.iv_callto_landload:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + "10000"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
                break;
            case R.id.contact_server_layout:
                break;
            case R.id.btn_apply_house:
                createOrder();
                break;
        }
    }

    private void createOrder(){
        JSONObject object = new JSONObject();
        try {
            object.put("checkindate", checkInDate);
            object.put("checkoutdate", checkOutDate);
            object.put("resourceId", detailBean.resourceId);
            object.put("orderTitle", detailBean.resourceName);
            object.put("userId", SPUtils.getStringByKey(mContext, Constants.UserId));
            object.put("checknum", checkinPeoPles);
            object.put("reserveNum", "1");
            object.put("orderAmount", detailBean.resourcePrice * days);
            object.put("customerRemark", "");
            String paramJson = object.toString();

            Type type = new TypeToken<LzyResponse<PayInfoBean>>() {
            }.getType();
            ServerApi.<LzyResponse<PayInfoBean>>getData(type, Urls.createOrder, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading();
                        }
                    })//
                    .map(new Function<LzyResponse<PayInfoBean>, PayInfoBean>() {
                        @Override
                        public PayInfoBean apply(@NonNull LzyResponse<PayInfoBean> response) throws Exception {
                            return response.data;
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<PayInfoBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull PayInfoBean mPayInfo) {
                            Bundle bundle = new Bundle();
//                            bundle.putSerializable("orderDetail", detailBean);
                            bundle.putString("orderId", mPayInfo.orderId);
//                            bundle.putString("in_date", checkInDate);
//                            bundle.putString("out_date", checkOutDate);
//                            bundle.putInt("orderType", mPayInfo.orderType);
                            AndroidUtils.startNextActivity(getActivity(), PayOrderActivity.class, bundle, false);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            dismissLoading();
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
